package com.yutel.phone.xplayer.ui;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.yutel.phone.xplayer.R;
import com.yutel.phone.xplayer.XPlayerConfig;
import com.yutel.phone.xplayer.service.AirplayService;

public class AirplayNotifier {
	private static AirplayNotifier mAirplayNotifier;
	private final int NOTIFICATION_ID = 1;
	private boolean mChanged = true;
	private String mMessage = "stoped";
	private Context mContext;
	private NotificationManager mNotificationManager;
	private SharedPreferences mSharedPreferences;

	public static AirplayNotifier getInstance(Context context) {
		if (mAirplayNotifier == null) {
			mAirplayNotifier = new AirplayNotifier(context);
		}
		return mAirplayNotifier;
	}

	public void setMessage(String msg) {
		mMessage = msg;
	}
	public void setChanged(boolean changed) {
		mChanged = changed;
	}
	private AirplayNotifier(Context context) {
		mContext = context;
		mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		mSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(context);
	}

	public void updateNotification() {
		if (mSharedPreferences.getBoolean("received", false)) {
			this.enableNotification();
		} else {
			this.disableNotification();
		}
	}

	private void enableNotification() {
		// Intent to call to turn off AutoAnswer
		Intent notificationIntent = new Intent(mContext, XPlayerConfig.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
				notificationIntent, 0);

		// Create the notification
		Notification n = new Notification(R.drawable.ap, null, 0);
		n.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
		n.setLatestEventInfo(mContext,
				mContext.getString(R.string.notification_title), mMessage,
				pendingIntent);
		mNotificationManager.notify(NOTIFICATION_ID, n);
		if (mChanged) {
			new Thread(service).start();
		}
	}

	private void disableNotification() {
		mNotificationManager.cancel(NOTIFICATION_ID);
	}

	private Runnable service = new Runnable() {
		@Override
		public void run() {
			mChanged = false;
			if (mSharedPreferences.getBoolean("startserver", false)) {
				Intent airPlay = new Intent(mContext, AirplayService.class);
				mContext.startService(airPlay);
			} else {
				Intent airPlay = new Intent(mContext, AirplayService.class);
				mContext.stopService(airPlay);
			}
		}
	};
}
